<template>
  <div class="cmt-container">
    <h3>发表评论</h3>
    <hr />
    <textarea placeholder="请输入要评论的内容（120字以内）" maxlength="120" v-model="newComment"></textarea>

    <mt-button type="primary" size="large" @click="postComment">发表评论</mt-button>
    <div class="cmt-list" v-for="(item,index) in commentsList" :key="item.add_time">
      <div class="cmt-item">
        <div
          class="cmt-title"
        >第{{ index+1 }}楼&nbsp;&nbsp;用户：{{ item.user_name }}&nbsp;&nbsp;发表时间：{{ item.add_time | dateFormat }}</div>
        <div
          class="cmt-body"
        >{{ (item.content === 'undefined' || item.content === '') ?'No comment':item.content }}</div>
      </div>
    </div>

    <mt-button type="danger" size="large" plain @click="getMore">加载更多</mt-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      commentsList: [],
      pageIndex: 1,
      newComment: ""
    };
  },
  props: ["id"],
  created() {
    this.getCommmentsById();
  },
  methods: {
    getCommmentsById() {
      this.$http
        .get("api/getcomments/" + this.id + "?pageindex=" + this.pageIndex)
        .then(res => {
          if (res.body.status == 0) {
            this.commentsList = this.commentsList.concat(res.body.message);
            // console.log("Comments loading complete");
          } else {
            Toast("Loading error...");
          }
        });
    },

    getMore() {
      this.pageIndex++;
      this.getCommmentsById();
    },
    postComment() {
      if (this.newComment.trim() === "")
        return console.log("Must write something!");

      this.$http
        .post("api/postcomment/" + this.id, { content: this.newComment.trim() })
        .then(res => {
          if (res.body.status == 0) {
            let commentObj = {
              user_name: "Anonynous",
              add_time: Date.now(),
              content: this.newComment.trim()
            };

            this.commentsList.unshift(commentObj);

            // console.log("New comments complete");
            this.newComment = "";
          } else {
            Toast("Loading error...");
          }
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.cmt-container {
  h3 {
    font-size: 18px;
  }
  textarea {
    font-size: 14px;
    height: 85px;
    margin: 0;
  }
  .cmt-list {
    margin: 5px 0;
    .cmt-item {
      font-size: 13px;
      .cmt-title {
        line-height: 30px;
        background-color: #ccc;
      }
      .cmt-body {
        line-height: 35px;
        text-indent: 2em;
      }
    }
  }
}
</style>>